package com.haruhinav.service.impl;

import com.haruhinav.Utils.Constants;
import com.haruhinav.Utils.FileUtil;
import com.haruhinav.entity.Wallpaper;
import com.haruhinav.entity.vo.ImageDetails;
import com.haruhinav.entity.vo.ResultVO;
import com.haruhinav.mapper.WallpaperMapper;
import com.haruhinav.service.WallpaperService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class WallpaperServiceImpl implements WallpaperService {

    @Autowired
    private WallpaperMapper wallpaperMapper;

    @Autowired
    private FileUtil fileUtil;

    /**
     * 上传图片后将路径和resize后的图片路径存进数据库
     * @param wallpaper
     * @return
     */
    @Override
    public int insert(Wallpaper wallpaper) {
        return wallpaperMapper.insert(wallpaper);
    }

    /**
     * 分页获取壁纸
     * map key : list count
     * @param wallpaper
     * @return
     */
    @Override
    public Map<String,Object> limitWallpaper(Wallpaper wallpaper) {
        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("list", wallpaperMapper.limitWallpaper(wallpaper));
        resMap.put("count", wallpaperMapper.countWallpaper(wallpaper));

        return resMap;
    }

    /**
     * 上传壁纸
     * admin和用户公用
     *
     * 图片不能回滚 只能数据库回滚
     * @param file
     * @param request
     * @param isAdmin
     * @return
     * @throws IOException
     */
    @Override
    @Transactional
    public ResultVO upload(MultipartFile file, ImageDetails details, HttpServletRequest request, boolean isAdmin) throws IOException {
        ResultVO result = new ResultVO();

        // 新文件名 uuid.suffix
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFileName = uuid+"."+details.getSuffix();

        // linux
        String path = fileUtil.getLinuxPath(request);
        // windows
//        String path = fileUtil.getWindowsPath();
        File file1 = new File(path);
        if(!file1.exists()){
            file1.mkdirs();
        }
        File dest = new File(file1 + "/" + newFileName);
        try {
            file.transferTo(dest);
            // 压缩图片
            String resizeName = fileUtil.resizeImage(dest,request,430,285);
            // 输入插入壁纸数据
            Wallpaper wallpaper = new Wallpaper();
            wallpaper.setName(newFileName);
            wallpaper.setUrl("/upload/"+newFileName);
            wallpaper.setResizeName(resizeName);
            wallpaper.setResizeUrl("/upload/resize/"+resizeName);
            wallpaper.setSize(details.getSize());
            wallpaper.setWidth(details.getWidth());
            wallpaper.setHeight(details.getHeight());
            wallpaper.setMd5(details.getMd5());
            wallpaper.setEnabled(isAdmin);
            if(wallpaperMapper.insert(wallpaper)<=0){
                result.setCode(-3);
                result.setMsg("路径保存到数据库失败!");
//                result.setData(newFileName);
            }
            result.setCode(0);
            if(isAdmin){
                result.setMsg("上传成功");
            }else {
                result.setMsg("上传成功,等待管理员审核！");
            }
            //(算了,突然发现就算是管理员上传也用不到uuid名)
            // result.setData(newFileName);
        } catch (IOException e) {
            result.setCode(-2);
            result.setMsg("上传失败");
            result.setType("error");
            e.printStackTrace();

        }
        return result;
    }

    @Override
    public Integer updateWallpaper(Wallpaper wallpaper) {
        return wallpaperMapper.updateWallpaper(wallpaper);
    }

    @Override
    public Integer deleteWallpaper(Wallpaper wallpaper,HttpServletRequest request) {
        // 删除服务器文件
        fileUtil.deleteFile(wallpaper.getName(),wallpaper.getResizeName(),request);
        return wallpaperMapper.deleteWallpaperById(wallpaper.getId());
    }

    /**
     * 批量删除by ids
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Integer batchDeleteByIds(long[] ids,HttpServletRequest request) {
        // 这个集合的对象里只有name resizeName enabled
        List<Wallpaper> list = wallpaperMapper.getWallpaperByIds(ids);
        if(list.size()<=0){
            return 0;
        }

        list.forEach(wallpaper -> {
            fileUtil.deleteFile(wallpaper.getName(),wallpaper.getResizeName(),request);
        });

        return wallpaperMapper.batchDeleteByIds(ids);
    }

    /**
     * 批量审核/下架
     * @param ids
     * @return
     */
    @Override
    public Integer batchUpdateEnabled(long[] ids) {

        // long[] ids = list.stream().mapToLong(Wallpaper::getId).toArray();


        return wallpaperMapper.batchUpdateEnabled(ids);
    }

    /**
     * 查询md5值相同的数据
     * @return
     */
    @Override
    public List<Wallpaper> getWallpaperGroupByMd5() {
        return  wallpaperMapper.getWallpaperGroupByMd5();
    }


}
